#!/bin/bash

# insert/update hosts entry

nw_input_option=$1

if [[ $nw_input_option != 1 && $nw_input_option != 2 ]]; then
	printf "\n纳网：您正在执行纳网处理host脚本，您要执行什么操作？\n1、添加host；\n2、删除添加的host；\n3、输入其它任意键退出。\n"
	read nw_input_option
	if [[ $nw_input_option != 1 && $nw_input_option != 2 ]]; then
		exit 0
	fi
fi

nw_host_file="/private/etc/hosts"
nw_comment="# 纳网科技"


nw_host_array=()


#需要添加或删除的域名
nw_host_array+=("117.78.16.62/qixinyi.cn")
nw_host_array+=("117.78.16.62/www.qixinyi.cn")
nw_host_array+=("117.78.16.62/m.qixinyi.cn")
nw_host_array+=("49.4.23.32/api.qixinyi.cn")
nw_host_array+=("49.4.23.32/api.gxzg.org.cn")
nw_host_array+=("49.4.23.32/agent.gxzg.org.cn")
nw_host_array+=("49.4.23.32/admin.xygw.org.cn")
nw_host_array+=("49.4.23.32/sdk.xygw.org.cn")
nw_host_array+=("58.83.224.222/na.wang")
nw_host_array+=("49.4.23.32/m.gxzg.org.cn")
nw_host_array+=("49.4.23.32/www.gxzg.org.cn")
nw_host_array+=("49.4.23.32/gxzg.org.cn")
nw_host_array+=("49.4.23.32/zhigouyi.cn")
nw_host_array+=("49.4.23.32/www.zhigouyi.cn")
nw_host_array+=("49.4.23.32/xinyongzhigou.com")
nw_host_array+=("49.4.23.32/www.xinyongzhigou.com")


echo "纳网：如果需要，请输入您的电脑密码。"


sudo sed -i "" "/${nw_comment}/d" ${nw_host_file}
for host in ${nw_host_array[@]}
do
	nw_temp_delete_array=(${host//// }) 
	sudo sed -i "" "/[[:space:]]${nw_temp_delete_array[1]}/d" ${nw_host_file}
done

if [[ $nw_input_option == 2 ]]; then
	exit 0
fi

echo "${nw_comment} 开始" | sudo tee -a ${nw_host_file} > /dev/null

nw_fun_add_host () {
	local nw_ip_address=$1
	local nw_host_name=$2
	echo "纳网：正在添加域名=>${nw_host_name}。"

	nw_matches_in_hosts="$(grep -n \"[[:space:]]$nw_host_name\" ${nw_host_file} | cut -f1 -d:)"
	nw_host_entry="${nw_ip_address} ${nw_host_name}"


	if [ ! -z "$nw_matches_in_hosts" ]
	then
	    # iterate over the line numbers on which matches were found
	    while read -r line_number; do
	        # replace the text of each line with the desired host entry
	        sudo sed -i '' "${line_number}s/.*/${nw_host_entry} /" /etc/hosts
	    done <<< "$nw_matches_in_hosts"
	else
	    echo "$nw_host_entry" | sudo tee -a ${nw_host_file} > /dev/null
	fi
}

for host in ${nw_host_array[@]}
do
	nw_temp_add_array=(${host//// }) 
	nw_fun_add_host ${nw_temp_add_array[0]} ${nw_temp_add_array[1]}
done

echo "${nw_comment} 结束" | sudo tee -a ${nw_host_file} > /dev/null
